﻿using DynamicExpresso;
using RAP.Framework.Libary.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace RAP.Framework.Libary.DataSource.Model.Setter
{
    /// <summary>
    /// 对象属性值赋值器
    /// </summary>
    public class PropertyValueSetter : IPropertyValueSetter
    {
        private static Interpreter _interpreter = new Interpreter();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataModelType"></param>
        /// <param name="property"></param>
        /// <param name="propertyType"></param>
        public PropertyValueSetter ( Type dataModelType, string property, Type propertyType )
        {
            //利用DynamicExpresso编译赋值表达式
            var action = _interpreter.Parse(
                $"model.{property} = value",
                new Parameter( "model", dataModelType ),
                new Parameter( "value", propertyType )
            );
            this.SetValue = ( dataModel, value ) =>
            {
                action.Invoke( dataModel, value );
            };
        }

        /// <summary>
        /// 对属性赋值
        /// </summary>
        public Action<object, object> SetValue { get; protected set; }
    }
}
